package com.leetcode.根据数据结构分类.字符串;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: ZhouBert
 * @date: 2021/2/25
 * @description: 14. 最长公共前缀
 * https://leetcode-cn.com/problems/longest-common-prefix/
 */
public class A_14_最长公共前缀 {

	public static void main(String[] args) {
		A_14_最长公共前缀 action = new A_14_最长公共前缀();
		test1(action);
	}

	public static void test1(A_14_最长公共前缀 action) {
		// ""
		String[] strs = new String[]{""};
		String res = action.longestCommonPrefix(strs);
		System.out.println("res = " + res);
	}


	public String longestCommonPrefix(String[] strs) {
		int len = strs.length;
		if (len == 0) {
			return "";
		}
		List<char[]> list = new ArrayList<>(len);
		int min = strs[0].length();
		for (int i = 0; i < len; i++) {
			char[] chars = strs[i].toCharArray();
			min = Math.min(min, chars.length);
			list.add(chars);
		}
		for (int i = 0; i < min; i++) {
			char c = list.get(0)[i];
			for (int j = 1; j < len; j++) {
				if (c != list.get(j)[i]) {
					return new String(list.get(0), 0, i);
				}
			}
		}
		return new String(list.get(0), 0, min);
	}
}
